// 导入依赖的模块
yepjs.require("jquery");
yepjs.require("YBA.Common");
yepjs.require("YBA.Plugin.plugins");
yepjs.require("YBA.Data.Terminal");
yepjs.require("YBA.Data.User");


// 终端管理 - 更新终端
yepjs.define("update", {

    NS: "YBA.Logic.Terminal",

    field: function() {

        var Biz = {
            // 初始化事件
            init: function() {
                Biz.vars.data={
                    "id":Biz.fn.GetQueryString("id")
                }
                Biz.fn.detail(Biz.vars.data);
                for (var i in Biz.event) {
                    Biz.event[i]();
                }
            },
            //  公共变量
            vars: {
                // 模板列表
                tpl: (function(){
                    var tpl = {};
                    $("script[type='text/ysmart']").each(function(){
                        var t = $(this);
                        tpl[t.attr("data-name")] = t.html();
                    });
                    return tpl;
                })(),
                // 新增人员搜索字段
                userVar: {
                	startPos: 1,
                    pageSize: 10,
                    departId: "",
                    mobile: "",
                    name: "",
                    username: ""
                },
                // 列表项目的总数量
                totalNum: 0,
                // 分页控件引用
                pageCtrl: null,
                //暂定空参
                data:{}
            },
            // 页面元素
            el: {
                body: $("body"),
                row:$(".row"),
                jform:$("#j-form")
            },
            // 功能函数集合
            fn: {
                //获取地址栏参数
                GetQueryString:function (parameterName){
                     var reg = new RegExp("(^|&)"+ parameterName +"=([^&]*)(&|$)");
                     var r = window.location.search.substr(1).match(reg);
                     if(r!=null)return  unescape(r[2]); return null;
                },
                // 表单验证
                formCheck: function(name) {

                	// 显示错误信息
                    var showError = function(obj, msg) {
                        var msgDom = obj.siblings('.message');
                        var msgTxt = msgDom.children('i')
                        msgDom.addClass("msg-error").removeClass('msg-tip');
                        msgTxt.html(msg);
                        msgDom.show();
                    };

                    // 隐藏错误信息
                    var hideError = function(obj, msg) {
                        var msgDom = obj.siblings('.message');
                        var msgTxt = msgDom.children('i')
                        msgDom.hide();
                        msgDom.addClass("msg-tip").removeClass('msg-error');
                        msgTxt.html(msg);
                    };

                    // 数据验证对象
                    var dataCheck = {
                        name:{
                            obj: Biz.el.jform.find("[name='name']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入终端名称");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,255)){
                                	showError(this.obj,"终端名称过长");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入终端名称");
                                    return true;
                                }
                            }
                        },
                        description: {
                            obj: Biz.el.jform.find("[name='description']"),
                            fn: function() {
                                if (this.obj.length <= 0) {return true;};
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入终端描述");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入终端描述");
                                    return true;
                                }
                            }
                        }
                    };

                    if (name && dataCheck[name]) {
                        return dataCheck[name].fn();
                    } else {
                        var errLen = 0;
                        for (var i in dataCheck) {
                            if (!dataCheck[i].fn()) {
                                errLen++;
                            }
                        }
                        if (errLen > 0) {
                            return false;
                        }
                        return true;
                    }
                },
                // 终端详情
                detail: function(data) {
                    YBA.Data.Terminal.getTerminalDetail(data, function(json){
                        if(json.code == 200) {
                            Biz.el.jform.html(YBA.Common.ysmart(Biz.vars.tpl.detailFormTpl, json.obj));
                        }else{
                            YBA.Plugin.msgtip({type: "i", msg: json.desc})
                        }
                    });
                },
                //新增预警/授权人员弹窗
                addUserTpl:function(obj,data){
                    var popform = new YBA.Plugin.popform({
                        title:obj.title,
                        className:"ui-dialog-user",
                        content:YBA.Common.ysmart(Biz.vars.tpl.userTpl,data.objList || {}),
                        width:654,
                        destroy:true,
                        onHide: function () {
                            // 隐藏弹窗时要执行的回调函数
                            Biz.vars.userVar.startPos = 1;
                        },
                        onShow:function(){
                            // 显示弹窗时要执行的回调函数
                            //复选框全选
                            YBA.Plugin.checkAll({
                                allObj:$(".j-checkAll"),
                                eachObj:$(".j-checkEach"),
                                list:$("#j-list")
                            });
                            $("#j-userTotalNum").html(data.page.totalRecord);
                            // 创建分页控件
                            Biz.vars.pageCtrl = new YBA.Plugin.pageNav({
                                // 放置分页控件的容器
                                pageCon: $("#j-userPage"),
                                // 每页数量
                                pageSize: Biz.vars.userVar.pageSize,
                                // 总数量
                                totalNum: Biz.vars.totalNum,
                                // 回调函数
                                callback: function (pageIndex) {
                                    // 设置页次
                                    Biz.vars.userVar.startPos = pageIndex;
                                    // 执行搜索
                                    Biz.fn.getList(function(json){
                                        $("#j-userList").html(YBA.Common.ysmart(Biz.vars.tpl.userListTpl,json.objList || {}));
                                    });
                                }
                            }).setTotalNum(data.page.totalRecord);
                        },
                        btns: [{
                            value: "确定",
                            className: "blue btn g-mr10",
                            fn: function () {
                                var data = {};
                                var i = 0;
                                var str = "";
                                $(".j-checkEach").each(function(){
                                    var t = $(this);
                                    if(t.is(':checked')){
                                        var tr = t.closest("tr"), id = tr.attr("data-id");
                                        data[i] = {
                                            "id":id,
                                            "name":tr.children('.tb-name').html(),
                                            "email":tr.children('.tb-email').html(),
                                            "mobile":tr.children('.tb-mobile').html()
                                        };
                                        i++;
                                    }
                                });
                                for(var n in data){
                                    str += '<tr data-id="'+data[n].id+'">' +
                                                '<td>'+data[n].name+'</td>' +
                                                '<td>'+data[n].email+'</td>' +
                                                '<td>'+data[n].mobile+'</td>' +
                                                '<td><a href="javascript:;" class="j-delUser">删除</a></td>' +
                                            '</tr>';
                                };
                                obj.fn(str);
                                popform.hide();
                            }
                        },{
                            value: "取消",
                            className: "red btn g-ml10",
                            fn: function () {
                                popform.hide();
                            }
                        }]

                    }).show();
                },
                //信息帮助弹窗
                helpDialog:function(data){
                    var popwin = new YBA.Plugin.popform({
                        width:500,
                        title:data.title,
                        content:data.msg,
                        destroy:true,
                        onHide: function () {
                            // 隐藏弹窗时要执行的回调函数
                        },
                        onShow: function () {
                            // 显示弹窗时要执行的回调函数
                        }
                    }).show();
                },
                // 读取人员列表
                getList: function (callback) {
                    YBA.Data.User.getUserList(Biz.vars.userVar, function (json) {
                        if(json.code == 200) {
                            callback && callback(json);
                        }else{
                            YBA.Plugin.msgtip({type: "i", msg: json.desc})
                        }
                    });
                },
                //预警/授权人员id赋值
                userIdStr:function(inp,list){
                    var userIdStr = "";
                    list.find('tr').each(function() {
                        var id = $(this).attr("data-id");
                        if(userIdStr == ""){
                            userIdStr = id
                        }else{
                            userIdStr = userIdStr+","+id;
                        };
                    });
                    inp.val(userIdStr);
                }
            },
            // 初始化时执行的所有事件
            event: {
                //初始化表单验证
                formCheck:function(){
                    Biz.el.jform.delegate(".required","blur",function(){
                        var t = $(this),
                        name = t.attr("name"),
                        holder = t.siblings(".message");
                        Biz.fn.formCheck(name);
                    }).delegate(".required","focus",function(){
                        var t = $(this),
                        name = t.attr("name"),
                        holder = t.siblings(".message");
                        holder.show();
                    });
                },
                //提交终端
                updateTerminal:function(){
                    Biz.el.jform.delegate("#j-updateBtn",'click', function() {
                        if (!Biz.fn.formCheck()) {
                            return false;
                        }else{
                        var form = Biz.el.jform.find("form");
                        var data ={};
                        Biz.fn.userIdStr($("#j-alertsId"),$("#j-alertUserList"));
                        Biz.fn.userIdStr($("#j-autsId"),$("#j-autUserList"));
                        data = form.serialize();
                        YBA.Data.Terminal.updateTerminal(data, function(json){
                            if(json.code == 200) {
                                YBA.Plugin.msgtip({type: "o", msg: "添加成功"});
                            }else{
                                YBA.Plugin.msgtip({type: "i", msg: json.desc});
                            }
                        });
                        }
                    });
                },
                //下载证书
                download:function(){
                    Biz.el.jform.delegate("#j-downloadBtn",'click', function() {
                        YBA.Data.Terminal.download(Biz.vars.data.id);
                    });
                },
                //刷新
                resetPage:function(){
                    Biz.el.jform.delegate("#j-resetBtn",'click', function() {
                        location.reload()
                    });
                },
                //新增预警人员
                addalertUser:function(){
                    Biz.el.jform.delegate("#j-alertUserBtn","click", function() {
                        var obj = {
                            title:"操作预警人员",
                            fn:function(str){
                                $("#j-alertUserList").append(str);
                            }
                        };
                        Biz.fn.getList(function(json){
                            Biz.fn.addUserTpl(obj,json);
                        });
                    });
                },
                //绑定设备特征查看具体信息
                whatInfo:function(){
                    Biz.el.jform.delegate(".j-whatInfo",'click', function() {
                        var data = {
                            "title":"查看具体信息",
                            "msg":"查看具体信息"
                        };
                        Biz.fn.helpDialog(data);
                    });
                },
                //了解加密算法
                whatEncrypt:function(){
                    Biz.el.jform.delegate(".j-whatEncrypt",'click', function() {
                        var data = {
                            "title":"了解加密算法",
                            "msg":"加密算法"
                        };
                        Biz.fn.helpDialog(data);
                    });
                },
                //关于证书文件
                whatFile:function(){
                    Biz.el.jform.delegate(".j-whatFile",'click', function() {
                        var data = {
                            "title":"关于证书文件",
                            "msg":"证书文件"
                        };
                        Biz.fn.helpDialog(data);
                    });
                },
                //选择是否加密显示加密信息内容
                isEncryptSrc:function(){
                    Biz.el.jform.delegate("#j-isEncryptSrc","click", function() {
                        if($(this).is(":checked")){
                            $(".j-radio").css("display","inline-block");
                        }else{
                            $(".j-radio").css("display","none");
                        }
                    });
                },
                //新增授权人员
                addautUser:function(){
                    Biz.el.jform.delegate("#j-autUserBtn","click", function() {
                        var obj = {
                            title:"操作授权人员",
                            fn:function(str){
                                $("#j-autUserList").append(str);
                            }
                        };
                        Biz.fn.getList(function(json){
                            Biz.fn.addUserTpl(obj,json);
                        });
                    });
                },
                //人员删除
                delUser:function(){
                    Biz.el.body.delegate('.j-delUser', 'click', function(event) {
                        var t = $(this),tr = t.closest('tr'),id = tr.attr("data-id");
                        tr.remove();
                    });
                }
            }
        };

        Biz.init();

        return Biz;
    }
});
